import _ from 'lodash';
import db from '../../xp/db';
import * as util from '../../../util';


let columns = 'id,code,username,avatar,name,nameJp,gender,' +
    'mobile,tel,officePhone,email,regionId,regionName,address,' +
    'ips,createTime,status,birthday,userType,openId,unionid,' +
    'institutionId,idCard';
columns = columns.split(',');
export function get(query, op, pageOpt) {
    return db.get('sys_users').query(qb => {
        if (query) {
            util.andWhere(query, op, qb);
        }
        qb.orderBy('createTime', 'desc');
    }).fetchPage({
        pageSize: pageOpt.pageSize,
        page: pageOpt.page,
        columns,
        withRelated: ['institution']
    });
}

export function getUser(query, op, orderby) {
    return db.get('sys_users').query(qb => {
        if (query) {
            util.andWhere(query, op, qb);
        }
        if (orderby) {
            console.log('xxxxxxxxxxxx orderby.keys:', _.keys(orderby));
            _.keys(orderby).forEach(k => {
                qb.orderBy(k, orderby[k]);
            });
        } else {
            qb.orderBy('createTime', 'desc');
        }
    }).list({
        columns,
        withRelated: ['institution']
    });
}

export function getUserWithRelate(query, op) {
    return db.get('sys_users').query(qb => {
        util.andWhere(query, op, qb);
    }).list({
        columns,
        withRelated: ['institution']
    });
}

export function getUserAllColumnsWithRelate(query, op) {
    return db.get('sys_users').query(qb => {
        util.andWhere(query, op, qb);
    }).list({
        withRelated: [{
            institution: qb => {
                qb.where({status: 1});
                qb.orderBy('displayOrder', 'asc');
            }
        }]
    });
}

export function add(user) {
    return db.get('sys_users').forge().save(user, {method: 'insert'});
}

export function edit(user) {
    return db.get('sys_users').where({id: user.id}).save(user, {method: 'update'});
}

export function del(id) {
    return db.get('sys_users')
        .where({id})
        .drop();
}
